package com.laicunba.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.laicunba.pojo.PicDO;
import com.laicunba.service.PicService;
import com.laicunba.util.StringUtil;

//@Service
public class PicServiceImpl extends BaseServiceImpl implements PicService {
	@Value("${pic.root}")
	private String root;

	@Value("${pic.path}")
	private String path;

	@Value("${pic.tmp}")
	private String tmpDir;

	private File tmpDirFile;
	private File rootDir;

	private File getTempDir() {
		if (tmpDirFile == null) {
			tmpDirFile = new File(tmpDir);
			if (!tmpDirFile.exists()) {
				tmpDirFile.mkdirs();
			}
		}
		return tmpDirFile;
	}

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/mm");

	@Override
	public PicDO createNewFile(DiskFileItem fileItem) {
		if (rootDir == null) {
			rootDir = new File(root);
			if (!rootDir.exists()) {
				rootDir.mkdirs();
			}
		}
		PicDO picDO = new PicDO();
		String names[] = fileItem.getName().split("[\\.]");
		String newFileName = sdf.format(new Date()) + "/" + StringUtil.genGUID() + "." + names[names.length - 1];
		File newFile = new File(rootDir, newFileName);
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(newFile);
			IOUtils.copy(fileItem.getInputStream(), fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		picDO.setPath(newFileName);
		picDO.setSize(fileItem.getSize());
		picDO.setName(fileItem.getName());
		picDO.setContentType(fileItem.getContentType());
		create(picDO);
		return picDO;
	}

   @Override
	public void upload2Ftp(InputStream inputStream, String destPath) {
		// TODO Auto-generated method stub
		
	}

}
